<?php
class Comm extends CI_Model {
	public function __construct() {
		parent::__construct();
		$this->load->database();
	}
	
	public function getMeta($title = NULL, $description = NULL, $keywords = NULL, $content = NULL) {
		$rs['title'] = $title.' ';
		$rs['keywords'] = $keywords;
		$rs['description'] = $description;
		$rs['content'] = $content;
		return $rs;
	}
	
	public function getUserCookie($cookieName = 'user') {
		$cookie = $this->getCookie($cookieName);
		if(!empty($cookie)) $this->setCookie($cookie, $cookieName);
		return $cookie;
	}
	
	public function getUserInfo($uid, $update = false) {
		if(empty($uid)) return NULL;
		$arrUser_info = json_decode($this->getUserCookie('user_info'), true);
		if(empty($arrUser_info) || $update == true) {
			$arrUser_info = $this->getRow('user_info', 'nick_name, my_pic, my_money, my_donate_money', array('uid'=>$uid));
			$this->setCookie(json_encode($arrUser_info), 'user_info');
		}
		return $arrUser_info;
	}
	
	public function getListPage($table, $arrWhere, $strGet, $orderBy = NULL, $numpage = 12) {
		$pn = $this->input->get('pn');
		$pn = empty($pn) ? 1 : $pn;
		$pn = !is_numeric($pn) ? 1 : $pn;
		$conut = $this->getCount($table, $arrWhere);
		$allPn = ceil($conut/$numpage);
		$pn = $pn > $allPn ? $allPn : $pn;
		$list = $this->getList($table, $strGet, $arrWhere, array($pn -1, $numpage), $orderBy);
		$pages = $this->getPageArray($allPn, $pn);
		return array('pn'=>$pn, 'allPn'=>$allPn, 'list'=>$list, 'pages'=>$pages);
	}
	
	public function getChannel($arrChannel = NULL, $parentcid = 0, $selfcid = "") {
		if(empty($arrChannel)) {
			if(!file_exists('./cache/channel.php')) {
				$this->createChannelFile();
			}
			include('./cache/channel.php');
			$arrChannel = $rs;	
		}
		if($parentcid == 0 && $selfcid == "") return $arrChannel;
		if($parentcid > 0) {
			$arrChannelChild = NULL;
			$depth = -1;
			$begin = false;
			foreach($arrChannel as $k => $v) {
				if($v['depth'] <= $depth) break;
				if($begin) $arrChannelChild[] = $v;
				if($v['cid'] == $parentcid) {$depth = $v['depth']; $arrChannelChild[] = $v;$begin = true;}
			}
			return $arrChannelChild;
		}
		if($selfcid != "") {
			foreach($arrChannel as $k => $v) {
				if($v['cid'] == $selfcid) return $v;
				if($v['en_title'] == $selfcid) return $v;
			}
		}
		return NULL;
	}
	
	public function attribute($cid = NULL, $return = false) {
		$arrJson = NULL;
		$cid = !empty($cid) ? $cid : $this->input->get('cid');
		$arrExtend['orderBy'] = 'cid asc, father_id asc, orders asc, aid asc';
		$attribute = $this->getTableCache('attribute', NULL, false, NULL, $arrExtend);
		$arrExtend['orderBy'] = 'cid asc, pid asc';
		$property = $this->getTableCache('property', NULL, false, NULL, $arrExtend);
		if(!empty($attribute)) {
			if($cid > 0) {
				foreach($attribute as $k => $v) {
					if($v['cid'] == 0 || $v['cid'] == $cid) $arrJson['attribute'][] = $v;
				}
			} else {
				$arrJson['attribute'] = $attribute;
			}
		} 
		if(!empty($property)) {
			if($cid > 0) {
				foreach($property as $k => $v) {
					if($v['cid'] == 0 || $v['cid'] == $cid) $arrJson['property'][] = $v;
				}
			} else {
				$arrJson['property'] = $property;
			}
		}
		if($return) return $arrJson;
		echo json_encode($arrJson);
	}	

	public function createChannelFile() {
		$this->load->helper('file');
		$arrChannel = $this->getList('channel', 'cid, channel, title, en_title, parent, children, depth, orders, display, out_url', NULL, NULL,
			array('orderBy'=>'channel asc, orders asc'));
		if(!empty($arrChannel)) {
			foreach($arrChannel as $k => $v) {
				if(!empty($v['out_url'])) {
					$arrChannel[$k]['url'] = $v['out_url'];
				} else {
					$urlExt = !empty($v['en_title']) ? $v['en_title'] : $v['cid'];
					$arrChannel[$k]['url'] = $this->config->base_url() . 'channel-' . $urlExt . '/';
				}
			}
		}
		$contant = $this->arrayTurnStr($arrChannel);
		if(empty($contant)) $contant = "''";
		$contant = "<?php \n".'$rs'." = ".$contant."; \n ?>";
		write_file('./cache/channel.php', $contant);	
	}
	
	public function getTableCache($table, $arrWhere = NULL, $getRow = false, $arrRowID = NULL, $arrExtend = NULL, $fileId = NULL) {
		$dir = './cache/';
		if($fileId > 0) $dir = $dir . $this->createCacheDir($fileId);
		$file = $dir.$table.$fileId.'.php';
		if(!file_exists($file)) {
			$this->createTableCache($table, $arrWhere, $getRow, $arrExtend, $fileId);
		}
		include($file);
		if(is_array($arrRowID) && !empty($rs)) {
			foreach($rs as $k => $v) {
				if($v[$arrRowID[0]] == $arrRowID[1]) return $v;
			}
			return NULL;
		}
		return $rs;	
	}
	
	public function createTableCache($table, $arrWhere = NULL, $getRow = false, $arrExtend = NULL, $fileId = NULL) {
		$this->load->helper('file');
		if($getRow) {
			$arrSiteinfo = $this->getRow($table, '*', $arrWhere);
		} else {
			$arrSiteinfo = $this->getList($table, '*', $arrWhere, NULL, $arrExtend);
		}
		$this->createCache($table, $arrSiteinfo, $fileId);
	}

	public function createCache($table, $arrSiteinfo, $fileId = NULL) {
		$dir = './cache/';
		if($fileId > 0) $dir = $dir . $this->createCacheDir($fileId);
		$contant = $this->arrayTurnStr($arrSiteinfo);
		if(empty($contant)) $contant = "''";
		$contant = "<?php \n".'$rs'." = ".$contant."; \n ?>";
		write_file($dir.$table.$fileId.'.php', $contant);
	}
	public function tableHash($key, $arrTableValue, $key_filter = NULL, $key_value = NULL, $switch = 'eq') {
		if(empty($arrTableValue)) return NULL;
		$arrHash = NULL;
		foreach($arrTableValue as $k => $v) {
			if(!empty($key_filter) && $key_value != '') {
				if($switch == 'eq') {
					if($v[$key_filter] == $key_value) $arrHash[$v[$key]] = $v;;
				} 
				if($switch != 'eq') {
					if($v[$key_filter] != $key_value) $arrHash[$v[$key]] = $v;;
				}
 			} else {
				$arrHash[$v[$key]] = $v;
			}
		}
		return $arrHash;
	}
	//
	//db exc
	public function getList($table, $selectFild = NULL, $arrWhere = NULL, $arrLimit = NULL, $arrExtend = NULL) {
		if(!empty($selectFild)) $this->db->select($selectFild);
		if(!empty($arrWhere)) $this->db->where($arrWhere);
		if(!empty($arrExtend)) {
			if(isset($arrExtend['orderBy']) && !empty($arrExtend['orderBy'])) $this->db->order_by($arrExtend['orderBy']);//str 
			if(isset($arrExtend['whereIn']) && !empty($arrExtend['whereIn'])) $this->db->where_in($arrExtend['whereIn'][0], $arrExtend['whereIn'][1]);
			if(isset($arrExtend['Like']) && !empty($arrExtend['Like'])) {
				foreach($arrExtend['Like'] as $k => $v) {
					$this->db->like($k, $v);
				}
			}
			if(isset($arrExtend['groupBy']) && !empty($arrExtend['groupBy'])) $this->db->group_by($arrExtend['groupBy']);
		}
		if(!empty($arrLimit) && is_array($arrLimit)) $this->db->limit($arrLimit[1], $arrLimit[0]);
		$query = NULL;
		
		$query = $this->db->get($table);
		$arrResult = NULL;
		foreach ($query->result_array() as $row) {
			$arrResult[] = $row;
		}
		return $arrResult;
	}
	
	public function getRow($table, $selectFild = NULL, $arrWhere = NULL) {
		$arrRow = $this->getList($table, $selectFild, $arrWhere);
		if(!empty($arrRow) && isset($arrRow[0])) return $arrRow[0];
		return NULL;
 	}
	public function getOne($table, $selectFild, $arrWhere = NULL) {
		$arrRow = $this->getList($table, $selectFild, $arrWhere);
		if(!empty($arrRow) && isset($arrRow[0][$selectFild])) return $arrRow[0][$selectFild];
		return NULL;
 	}
	public function getCount($table, $arrWhere = NULL) {
		return $this->getOne($table, 'count(*)', $arrWhere);
 	}
	public function insert($table, $arrData, $insert_batch = false) {
		if($insert_batch) return $this->db->insert_batch($table, $arrData);
		return $this->db->insert($table, $arrData); 
	}
	
	public function getInsertId() {
		return $this->db->insert_id();
	}
	
	public function update($table, $arrData, $arrWhere) {
		return $this->db->update($table, $arrData, $arrWhere); 
	}
	public function delete($table, $where) {
		return $this->db->delete($table, $where); 
	}
	public function set($key, $value, $trans = true) {
		return $this->db->set($key, $value, $trans); 
	}
	public function query($sql) {
		return $this->db->query($sql);
	}
	//
	public function setEtag($pname) {
		header("Etag: ".$pname);
	} 
	
	public function getEtag() {
		if(isset($_SERVER['HTTP_IF_NONE_MATCH'])) return $_SERVER['HTTP_IF_NONE_MATCH'];
		return NULL;
	} 
	public function getSelfUrl() {
		if(isset($_SERVER['REQUEST_URI'])) {
			return 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
		}
		return '';
	}
	public function getReferUrl() {
		if(isset($_SERVER['HTTP_REFERER'])) {
			return $_SERVER['HTTP_REFERER'];
		}
		if(isset($_SERVER['REQUEST_URI'])) {
			return 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
		}
		return '';
	}
	public function &arrayTurnStr($data) {
		$str = '';
		if(is_array($data)) {
			$str .= "array(";
			foreach($data as $k => $v) {
				if(is_array($v)) {
					$str .= "'$k' => ";
					$str .= $this->arrayTurnStr($v).',';
				} else {
					$str .= "'$k' => '$v',";
				}
			}
			$str = trim($str, ',').")";
		}
		return $str;
	}
	
	public function &addslashesStr($data) {
		if(is_array($data)) {
			foreach($data as $key => $val) {
				if(is_array($val)) {
					$data[$key] = $this->addslashesStr($val);
				} else {
					$data[$key] = addslashes($val);
				}
			}
		} else {
			$data = addslashes($data);
		}
		return $data;
	}

	public function &toHtml($data) {
		if(is_array($data)) {
			foreach($data as $key => $val) {
				if(is_array($val)) {
					$data[$key] = $this->toHtml($val);
				} else {
					$data[$key] = nl2br(str_replace(" ", "&nbsp;", $val));
				}
			}
		} else {
			$data = nl2br(str_replace(" ", "&nbsp;", $data));
		}
		return $data;
	}
	
	public function formatXmlSpecialChar($str) {
		return str_replace("'",'&apos;',str_replace('"','&quot;',str_replace('<','&lt;',str_replace('>','&gt;',str_replace('&','&amp;',$str)))));
	}
	
	public function cutString($str, $len, $start = 0) {
		if(strlen($str) <= $len) {
			return $str;
		}
		for($loop = 0; $loop < $len; $loop++) {
			if(ord($str[$loop]) > 224) {
				$loop += 2;
				continue;
			}
			if(ord($str[$loop]) > 192) {
				$loop++;
			}
		}
		/*if($loop == $len + 1) {
			$len--;
		}*/
		return substr($str, 0, $loop);
	}	
	
	public function getToken($value, $time = NULL) {
		return md5(md5(md5(md5($value) . $this->config->item('user_key')) . $this->config->item('encryption_key')) .$time);
	}
	public function encode($value) {
		$this->load->library('encrypt');
		return $this->encrypt->encode($value);
	}
	public function decode($value) {
		$this->load->library('encrypt');
		 return $this->encrypt->decode($value);
	}
	public function encrypt($txt, $key = 'xadfsdfsadfdsf%^&*') { 
		srand((double)microtime() * 1000000); 
		$encrypt_key = md5(rand(0, 32000)); 
		$ctr = 0; 
		$tmp = ''; 
		for($i = 0;$i < strlen($txt); $i++) { 
			$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; 
			$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]); 
		} 
		return base64_encode($this->passport_key($tmp, $key)); 
	} 
	
	public function decrypt($txt, $key = 'xadfsdfsadfdsf%^&*') { 
		$txt = $this->passport_key(base64_decode($txt), $key); 
		$tmp = ''; 
		for($i = 0;$i < strlen($txt); $i++) { 
			$md5 = $txt[$i]; 
			$tmp .= $txt[++$i] ^ $md5; 
		} 
		return $tmp; 
	} 

	public function passport_key($txt, $encrypt_key) { 
		$encrypt_key = md5($encrypt_key); 
		$ctr = 0; 
		$tmp = ''; 
		for($i = 0; $i < strlen($txt); $i++) { 
			$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; 
			$tmp .= $txt[$i] ^ $encrypt_key[$ctr++]; 
		} 
		return $tmp; 
	} 
	//
	public function setCookie($cookie_value, $cookieName = 'user') {
		$this->load->library('encrypt');
		$this->input->set_cookie(md5($cookieName), $this->encrypt->encode($cookie_value), $this->config->item('cookie_time'));
	}
	
	public function getCookie($cookieName = 'user') {
		$this->load->library('encrypt');
		return $this->encrypt->decode($this->input->cookie(md5($cookieName), true));
	}
	
	public function delCookie($cookieName = 'user') {
		$this->input->set_cookie(md5($cookieName), NULL, time() - 3600);
	}
	
	public function setSession($cookie_value, $cookieName = 'user') {
		if(!isset($_SESSION)){session_start();}
		$_SESSION[$cookieName] = $cookie_value;
	}
	
	public function getSession($cookieName = 'user') {
		if(!isset($_SESSION)){session_start();}
		if(isset($_SESSION[$cookieName])) return $_SESSION[$cookieName];
		return NULL;
	}
	
	public function delSession($cookieName = 'user') {
		if(!isset($_SESSION)){session_start();}
		if(isset($_SESSION[$cookieName])) unset($_SESSION[$cookieName]);
	}
	
	public function createDataDir($dir = NULL, $dataDir = './data/') {
		$d = date('Y');
		$m = date('m') . '-' . date('d');
		//$dataDir = $this->config->item('filedir');
		if(!empty($dir)) {$this->createDir($dataDir.$dir);}
		$this->createDir($dataDir.$dir.$d);
		$this->createDir($dataDir.$dir.$d.'/'.$m);
		return $d.'/'.$m.'/';
	}
	
	public function createCacheDir($id, $dir = 'attr/') {
		$cacheDir = './cache/';
		if(!empty($dir)) {$this->createDir($cacheDir.$dir);}
		$dir_id = $this->creatNumFileId($id) . '/';
		$this->createDir($cacheDir.$dir.$dir_id);
		return $dir . $dir_id;
	}
	
	public function createDir($dir, $mode = 0777) {
		if(is_dir($dir)){
			return;
		} 
		if(mkdir($dir) == false) {
			throw new Exception(".error: can't create dir $dir.");
		}
		return chmod($dir, $mode);
	}
	
	public function creatNumFileId($id, $len = 3, $max = 0, $ext = NULL) {
		if($max > 0) $id = $id % $max;
		$id_len = strlen($id);
		if($id_len >= $len) {
			$fileid = substr($id, -$len);
		} else {
			$i_len = '000000000000000000';
			$fileid = substr($i_len,$id_len - $len) . $id;
		} 
		return $ext . $fileid;
	}
	
	public function getPageArray($allpage, $pn, $pass_pn = 5, $pn_length = 10) {
		$arrPages = NULL;
		$i = 0;
		$k = 0;
		$pass = 0;
		if($pn > 1) {
			$arrPages[$i]['title'] = '&laquo;';
			$arrPages[$i]['pn'] = $pn - 1;
			$i++;
		}
		if($allpage <= $pn_length) {
			if($pn > 1) {
				for($i; $i <= $allpage; $i++) {
					$arrPages[$i]['title'] = $i;
					$arrPages[$i]['pn'] = $i;
				}
			} else {
				for($i; $i < $allpage; $i++) {
					$arrPages[$i]['title'] = $i + 1;
					$arrPages[$i]['pn'] = $i + 1;;
				}
			}
			$i--;
		} else {
			if($pn <= $pass_pn) {
				for($i; $i < $pn_length; $i++) {
					if($i == 0) continue;
					$arrPages[$i]['title'] = $i;
					$arrPages[$i]['pn'] = $i;
				}
			} else {
				$pass = $pn - $pass_pn - 1;
				if(($allpage - $pass) < $pn_length) $pass = $allpage - $pn_length;
				$arrPages[$i]['title'] = '1';
				$arrPages[$i]['pn'] = 1;
				$i++;
				$arrPages[$i]['title'] = '...';
				$arrPages[$i]['pn'] = '#pn';
				$i++;
				for($k; $k < $pn_length; $k++) {
					$arrPages[$i + $k]['title'] = $i + $k + $pass;
					$arrPages[$i + $k]['pn'] = $i + $k + $pass;
					if(($i + $k + $pass) == $allpage) break;
				}
				
			}
			if(($i + $k + $pass) == $allpage) {
				$arrPages[$i + $k]['title'] = $allpage;
				$arrPages[$i + $k]['pn'] = $allpage;
				$i = $i + $k;
			} else {
				$arrPages[$i + $k]['title'] = '...';
				$arrPages[$i + $k]['pn'] = '#pn';
				$arrPages[$i + $k + 1]['title'] = $allpage;
				$arrPages[$i + $k + 1]['pn'] = $allpage;
				$i = $i + $k + 1;
			}
		}
		if($pn < $allpage) {
			$arrPages[$i + 1]['title'] = '&raquo;';
			$arrPages[$i + 1]['pn'] = $pn + 1;
		}
		return $arrPages;			
	}
	
	public function downcode($uid, $rid) {
		return md5(date('YmdH').md5($uid).md5($rid).md5($this->config->item('encryption_key')));
	}
}